#include "hardwareinterfaceview.hpp"
#include "ui_hardwareinterfaceview.h"

HardwareInterfaceView::HardwareInterfaceView(QWidget *parent) :
    QDockWidget(parent),
    ui(new Ui::HardwareInterfaceView)
{
    ui->setupUi(this);
    connect(ui->btn_ManualSend, SIGNAL(clicked()), this, SIGNAL(manualSend()));

    this->serialWatcher = new SerialDeviceWatcher();
    connect(this->serialWatcher, SIGNAL(hasChanged(QStringList)), this, SLOT(onSerialDevicesChanged(QStringList)));

    this->onSerialDevicesChanged(this->serialWatcher->devicesAvailable());
}

HardwareInterfaceView::~HardwareInterfaceView()
{
    delete ui;
    this->serialWatcher->deleteLater();
}

void HardwareInterfaceView::changeEvent(QEvent *e)
{
    QDockWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}


void HardwareInterfaceView::onSerialDevicesChanged(QStringList devices)
{
    devices.sort();

    QString old = ui->db_ComPort->currentText();

    ui->db_ComPort->clear();
    ui->db_ComPort->addItem("None");

    for (int i = 0; i < devices.size(); i++)
    {
	ui->db_ComPort->addItem(devices.at(i));

	if (old == devices.at(i))
	    ui->db_ComPort->setCurrentIndex(i + 1);
    }
}


void HardwareInterfaceView::on_cb_Activated_clicked()
{
    ui->db_ComPort->setEnabled(!ui->cb_Activated->isChecked());

    emit changeHardwareInterfaceState(ui->db_ComPort->currentText(), ui->cb_Activated->isChecked());
}


void HardwareInterfaceView::on_db_ComPort_currentIndexChanged(int index)
{
    ui->cb_Activated->setChecked(false);
    ui->cb_Activated->setEnabled(index != 0);
}


void HardwareInterfaceView::on_btn_ManualReceive_clicked()
{
    emit manualReceive(ui->ln_ManualReceive->text());
}


void HardwareInterfaceView::onHardwareInterfaceStateChanged(bool state)
{
    ui->btn_ManualReceive->setEnabled(state);
    ui->btn_ManualSend->setEnabled(state);
    ui->ln_ManualReceive->setEnabled(state);
    ui->db_ComPort->setEnabled(!state);
    ui->ln_LastReceived->clear();
    ui->ln_LastSent->clear();
    ui->ln_LastReceivedOn->clear();
    ui->ln_LastSentOn->clear();

    if (!state)
	ui->cb_Activated->setChecked(false);
}


void HardwareInterfaceView::onError(QString device, QString errorString)
{
    QMessageBox::warning(this, tr("Failed to connect to Serial Port"), "The connection to Port " + device + " has failed:\n" + errorString);
}


void HardwareInterfaceView::onDataRead(QString data)
{
    ui->ln_LastReceived->setText(data);
    QTime time;
    time.start();
    ui->ln_LastReceivedOn->setText(time.toString("HH:mm:ss.zzz"));
}


void HardwareInterfaceView::onDataWritten(QString data)
{
    ui->ln_LastSent->setText(data);
    QTime time;
    time.start();
    ui->ln_LastSentOn->setText(time.toString("HH:mm:ss.zzz"));
}
